package com.damie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.damie.common.jwtuilts.JwtUtil;
import com.damie.domain.WasteOrder;
import com.damie.domain.WasteOrderDetails;
import com.damie.exception.MyException;
import com.damie.mapper.WasteOrderDetailsMapper;
import com.damie.mapper.WasteOrderMapper;
import com.damie.param.OrderPageParam;
import com.damie.service.WasteOrderService;
import com.damie.utils.MyRunnable;
import io.jsonwebtoken.Claims;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Alon
 * @since 2021-01-19
 */
@Service
public class WasteOrderServiceImpl extends ServiceImpl<WasteOrderMapper, WasteOrder> implements WasteOrderService {
    @Resource
    private WasteOrderMapper wasteOrderMapper;

    @Resource
    private WasteOrderDetailsMapper wodm;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private StringRedisTemplate srt;

    /**
     * 订单分页查询
     * @param orderPageParam 查询语句条件
     * @return
     */
    @Override
    public List<WasteOrder> pageInfo(OrderPageParam orderPageParam, HttpServletRequest request) {

        //获取当前登录的token
        String token = request.getHeader("token");
        Claims claims = JwtUtil.parseToken(token);
        Object userId = claims.get("userId");
        String id = userId.toString();

        Page<WasteOrder> page1 = wasteOrderMapper.selectPage(orderPageParam.getPage(), new QueryWrapper<WasteOrder>()
                .eq("user_id", id)
                .eq("waste_order_status",orderPageParam.getStatus()));//1351497207160848386
        List<WasteOrder> records = page1.getRecords();
        return records;
    }

    /**
     * 查询订单详情
     * @param wasteOrderId
     * 根据订单id查询
     * @return
     */
    @Override
    public List<WasteOrderDetails> detailsInfo(String wasteOrderId) {
        List<WasteOrderDetails> waste_order_id = wodm.selectList(new QueryWrapper<WasteOrderDetails>().eq("waste_order_id", wasteOrderId));
        return waste_order_id;
    }

    /**
     * 催单功能
     * @param oid 根据订单id催单
     * @return
     */
    @Override
    public Boolean press(String oid) {
        WasteOrder wasteOrder = wasteOrderMapper.selectOne(new QueryWrapper<WasteOrder>().eq("waste_order_id", oid));
        if (ObjectUtils.isEmpty(wasteOrder)){
           throw new MyException(20011,"该订单不存在");
        }
        if (wasteOrder.getWasteOrderStatus() == 1){
            //向rocketmq里面，向所有骑手推送接单消息
            Message<String> message = MessageBuilder.withPayload("当前订单号："+wasteOrder.getWasteOrderId()+"，没有被接单，请派骑手接单")
                    .setHeader(MessageConst.PROPERTY_KEYS, UUID.randomUUID().toString())
                    .build();
            rocketMQTemplate.syncSendOrderly("damie:press", message, "message");
            //记录当前时间
            long currTime = System.currentTimeMillis();
            //redis中记录 0=》未接单 1 =》接单      就释放锁取消订单
            srt.opsForValue().set("press:"+wasteOrder.getWasteOrderId(),0+"");
            //延时器
            //当锁消失后,取消订单状态

                //延时器
                Timer timer = new Timer();
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        //查询redis中的状态
                        String s = srt.opsForValue().get("press:" + wasteOrder.getWasteOrderId());
                        if (!StringUtils.isEmpty(s)){
                            //如果订单人接单则15分钟后取消订单
                            if (s.equals("0")){
                                //取消订单，更改状态
                                wasteOrder.setWasteOrderStatus(4);
                                wasteOrderMapper.updateById(wasteOrder);
                                throw new MyException(20015,"已为您取消订单,请重新定位下单");
                            }else if (s.equals("1")){
                                throw new MyException(20011,"骑手已接待,请稍等");
                            }
                        }
                    }
                };
            //15分钟后去回查看订单是否被接单
            timer.schedule(task, 15*1000*60);

        }else {
            throw new MyException(20012,"该订单已被骑手接单");
        }
        return true;
    }
}
